package GUI;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class MazeArea extends JPanel implements CellChangedListener, SizeChangedListener {

	private Cell[][] grid = { {new Cell(0,0)}};
	private int cellwidth = 15, cellheight = 15;
	private int xcount = 1, ycount = 1;
	private final int PLUSMINUS = 1;

	private final int PADDING = 50;

	private Dimension d = new Dimension(PADDING, PADDING);

	public MazeArea() {
		init();
	}

	public void init() {
		setLayout(new FlowLayout(FlowLayout.CENTER));
		setBackground(Color.WHITE);
	}

	public void setWH(int x, int y) {
		removeAll();
		grid = new Cell[y][x];
		xcount = x;
		ycount = y;

		d.setSize(cellwidth * x + PADDING * 2, cellheight * y + PADDING * 2);
		setMaximumSize(d);
		setPreferredSize(d);

		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[i].length; j++) {
				grid[i][j] = new Cell(j, i);
				grid[i][j].addCellChangedListener(this);
			}
		}
	}

	@Override
	public void paint(Graphics g) {
		try {
			super.paint(g);
		} catch (Exception e) {
		}
		Graphics2D graphic = (Graphics2D) g;

		for (int i = 0; i < ycount; i++) {
			for (int j = 0; j < xcount; j++) {
				if (!grid[i][j].wallsIntact())
					paintCell(graphic, grid[i][j], cellwidth, cellheight);
			}
		}

	}

	private void paintCell(Graphics2D graphic, Cell c, int width, int height) {
		float f = (float) 2;
		BasicStroke bs = new BasicStroke(f);
		graphic.setStroke(bs);
		
		int xoffset = c.getPosx() * width + PADDING;
		int yoffset = c.getPosy() * height + PADDING;

//		if (!c.wallsIntact()) {
//			graphic.setColor(Color.WHITE);
//			graphic.fillRect(xoffset, yoffset, width, height);
//			graphic.setColor(Color.BLACK);
//
//		}
		graphic.setColor(Color.BLACK);

		if (c.isTop()) {
			graphic.drawLine(xoffset, yoffset, xoffset + width, yoffset);
		}
		if (c.isLeft()) {
			graphic.drawLine(xoffset, yoffset, xoffset, yoffset + height);
		}
		if (c.isRight()) {
			graphic.drawLine(width + xoffset, yoffset, width + xoffset, height + yoffset);
		}
		if (c.isBottom()) {
			graphic.drawLine(xoffset, height + yoffset, width + xoffset, height + yoffset);
		}
		
		//graphic.drawString(c.getGroup()+"", xoffset, yoffset+10);

	}

	public Cell[][] getGrid() {
		return grid;
	}

	@Override
	public void cellChanged() {
		updateUI();
	}

	@Override
	public void minus() {
		if (cellheight > PLUSMINUS && cellwidth > PLUSMINUS) {
			cellheight -= PLUSMINUS;
			cellwidth -= PLUSMINUS;
			d.setSize(cellwidth * xcount + PADDING * 2, cellheight * ycount + PADDING * 2);
			updateUI();
		}

	}

	@Override
	public void plus() {
		cellheight += PLUSMINUS;
		cellwidth += PLUSMINUS;
		d.setSize(cellwidth * xcount + PADDING * 2, cellheight * ycount + PADDING * 2);
		updateUI();
	}
}
